# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2020/09/13 18:40:00
@Author  :   Wicos 
@Version :   1.0
@Contact :   wicos@wicos.cn
@Blog    :   https://www.wicos.me
'''

# here put the import lib
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import main
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from starlette.requests import Request
from pydantic import BaseModel
import json
from model import data
import datetime
import time
from model import qr

app = FastAPI()
origins = ["*"]

class ADD(BaseModel):
    id:str
    date:str
    type:int
    content:str

class FROMTYPE(BaseModel):
    type:int
    num:int
    offset:int=None
    rows:int=None

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

templates = Jinja2Templates(directory="templates")
templates.env.variable_end_string = ']}' # 解决冲突
templates.env.variable_start_string = '{['
app.mount("/static", StaticFiles(directory="static"), name="static")

def jsonX(jsonfile):
    with open(jsonfile,'rb') as fp:
        a = json.load(fp)
    return a
config = jsonX("config.json")
sql_data = config["mysql"]
#mysql_con = data.CON(sql_data['ip'],sql_data['db'],sql_data['name'],sql_data["passwd"])


@app.get("/")
async def index(request: Request):
    return templates.TemplateResponse("index.html", {'request': request})

@app.post("/add")
async def add_fun(item:ADD):
    get_add = item.dict()
    #print(get_add)
    mysql_con = data.CON(sql_data['ip'],sql_data['db'],sql_data['name'],sql_data["passwd"])
    bc = mysql_con.add(get_add["id"],get_add["date"],get_add["type"],get_add["content"])
    if bc == 0:
        qrs = qr.creat_qr("http://send.paa.fun/detail/"+get_add['id'],get_add['id']+".png")
        if qrs['code'] == 0:
            return {"code":0,"msg":qrs["msg"]}

@app.get("/item/{num}")
async def item(num = 20):
    pass

@app.post("/fromtype")
async def fromid(item:FROMTYPE):
    mysql_con = data.CON(sql_data['ip'],sql_data['db'],sql_data['name'],sql_data["passwd"])
    from_type = item.dict()
    id_data = mysql_con.find_from_type(from_type["type"],offset=from_type["offset"],rows=from_type["rows"])
    return {"fromtype":id_data}

@app.post("/allitem")
async def allitem():
    mysql_con = data.CON(sql_data['ip'],sql_data['db'],sql_data['name'],sql_data["passwd"])
    all_data = mysql_con.get_data(20)
    return {"alldata":all_data}

@app.get("/webtime")
def webtime():
    ttime = datetime.date.today()
    rt = {
        "time":"{}-{}-{}".format(ttime.year,ttime.month,ttime.day),
        "id":int(time.time()*100)
    }
    return rt